import logging
import numpy as np
# from logging.handlers import SMTPHandler
# from backtest_optimize import Strategy
import threading
import time
"""----------------------------------------------初始化阶段----------------------------------------------------------"""
# logger = logging.getLogger('Yhlz')
# logger.setLevel(logging.DEBUG)
# fm = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#
# fh = logging.FileHandler('log.txt', mode='a')
# fh.setFormatter(fm)
# fh.setLevel(logging.DEBUG)

# mail_handler = SMTPHandler(
#         mailhost=('smtp.qq.com',587),
#         fromaddr='517353631@qq.com',
#         toaddrs='517353631@qq.com',
#         subject='running info! ',
#         credentials=('517353631@qq.com', 'kyntpvjwuxfvbiag'))
# mail_handler.setLevel(logging.INFO)
# mail_handler.setFormatter(fm)
#
# logger.addHandler(mail_handler)
# logger.addHandler(fh)
# logger.propagate = False
# logger.info('sec,try!')
# child = logging.getLogger('Yhlz.child')
# child.propagate = True
# child.debug('123')
print('iiii')
class TargetPosTaskSingleton(type):

    # def __new__(cls, class_name, class_parents, new_attr):
    #     print('012')
    #     return type(class_name, class_parents, new_attr)

    def __call__(cls, b):
        print(123)

    def aaa(cls):
        print(234)

class second():
    def __init__(self, b):
        self.b=b
        print(345)

from tqsdk import TqApi, TqAuth, TqKq

# api = TqApi(TqKq(), auth=TqAuth("18064114200", "86888196"))
# api = TqApi(auth=TqAuth("18064114200", "86888196"))
# quote = api.get_quote("SHFE.cu2112")
# print(quote)
# quote = api.get_kline_serial("SHFE.rb2205", 86400, 60)
# print(quote['datetime'].apply(lambda x: '%9f' %(x/(1000 **3))) )
# print(quote.loc[0,'datetime'] == 0)
# api.close()
# exit(0)
# print(quote)
# quote = api.get_kline_serial("CZCE.SR201", 60)
# print(quote)
# api.close()
# print(quote.last_price)
# while api.wait_update():
#     print(quote.last_price)

def tryy():
   time.sleep(5)

# tsObj = ts.pro_api('dddcca116f1989381f025f6bcc2cb8f3e5c6910ca222cfc2f286202e')
# df = tsObj.new_share(start_date='20200101', end_date='20201231')
# print()
# a=threading.Thread(target=tryy)
# a.start()
# a.join(timeout=1)
# print('timeout')
# a.join()
# print('ok')
# from flask import Flask
# app = Flask(__name__)
#
# @app.route('/')
# def hello_world():
#     with open('currentAccount.csv') as f:
#         return f.read()
#
# if __name__ == '__main__':
#     app.run()
# import tushare as ts
# import pandas as pd
# from datetime import datetime
# tsObj = ts.pro_api('dddcca116f1989381f025f6bcc2cb8f3e5c6910ca222cfc2f286202e')
# contractInfo = pd.concat(
#     [tsObj.fut_basic(exchange='SHFE'), tsObj.fut_basic(exchange='DCE'),
#      tsObj.fut_basic(exchange='CZCE'), tsObj.fut_basic(exchange='CFFEX'),
#      tsObj.fut_basic(exchange='INE')])
# contractInfo = contractInfo[contractInfo['delist_date'] > datetime.now().strftime('%Y%m%d')]
# print()

# from tqsdk.algorithm import Twap

# # 设置twap任务参数
# target_twap = Twap(api,"SHFE.rb2201","BUY","OPEN",50,30,10,25)
# # 启动循环
# while True:
#   api.wait_update()
#   if target_twap.is_finished():
#       break
# api.close()


import time
from tqsdk import TqApi, TqAuth, TqKq, TargetPosScheduler, TqAccount
from tqsdk.algorithm import twap_table
from tqsdk.channel import TqChan
import asyncio

import pandas as pd
import time
# from db_interface import *

# df = pd.DataFrame({'trade_id': '533a59235e214c1caca80c2b28eb713c'}, index=[0])
# write_signal("SHFE.rb2205", 'sma', time.time(), df, True, 5000)

# api = TqApi(TqKq(), auth=TqAuth("18064114200", "86888196"))

# write_orders(api.get_order())
# write_trades(api.get_trade())

# api.close()
# exit(0)
# api = TqApi()
# quote = api.get_quote("SHFE.rb2205")
# print(11111111111111111111)
# # 设置twap任务参数
# time_table = twap_table(api, "SHFE.rb2205", 0, 20, 1, 10)  # 目标持仓 -100 手，600s 内完成
# print(time_table.to_string())
# chan = TqChan(api)
# target_pos_sch = TargetPosScheduler(api, "SHFE.rb2205", time_table, trade_objs_chan=chan)
# async def tty():
#     print('*'*10)
#     while True:
#         await asyncio.sleep(1)
#         res = chan.recv_latest('nothing!')
#         print(res)

#     print('close!')
#     await chan.close()
#     print('closed')

# api.create_task(tty())
# 启动循环
# while not target_pos_sch.is_finished():
#     api.wait_update()
#     # print('update!')
# print('stop')
# print(target_pos_sch.trades_df)
# write_signal("SHFE.rb2205", 'sma', time.time(), target_pos_sch.trades_df, True, 5000)
# api.close()




from tqsdk import TqApi, TargetPosScheduler,TqAccount
from tqsdk.algorithm import twap_table

from tqsdk.ta import MA
# api = TqApi(auth="信易账户,用户密码")
# quote = api.get_quote("DCE.jd2201")

# 设置twap任务参数
# time_table = twap_table(api, "DCE.jd2201", 10, 60, 1, 5)  # 目标持仓 -100 手，600s 内完成
# print(time_table.to_string())

# target_pos_sch = TargetPosScheduler(api, "DCE.jd2201", time_table, offset_priority='昨开')
# 启动循环
api = TqApi(web_gui=True, auth=TqAuth("18064114200", "86888196"))
# 引入TqSdk模块
# 订阅 cu2002 合约的10秒线
# klines = api.get_kline_serial("SHFE.rb2210", 60)
# klines["ma_MAIN"] = klines['high'].max()
# while True:
    # 通过wait_update刷新数据
    # api.wait_update()


'''
画图示例: 在主图中画指标线
注意: 画图示例中用到的数据不含有实际意义，请根据自己的实际策略情况进行修改
'''

# api = TqApi(web_gui=True, auth=TqAuth("信易账户", "账户密码"))  # web_gui=True, 开启使用 web 界面查看绘图结果的功能
klines = api.get_kline_serial("SHFE.rb2210", 60)

# 画一次指标线
ma = MA(klines, 30)  # 使用 tqsdk 自带指标函数计算均线
klines["ma_MAIN"] = ma.ma  # 在主图中画一根默认颜色（红色）的 ma 指标线

# 由于需要在浏览器中查看绘图结果，因此程序不能退出
while True:
    api.wait_update()